package org.opens.apache.codec;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Base64ToString {

    Base64 base64 = new Base64();

    @Test
    public void test1() {
        String str = "张玉明";
        String base64str = base64.encodeToString(str.getBytes(StandardCharsets.UTF_8));
        System.out.println(base64str);
    }

    @Test
    public void test2() {
        String str = "张玉明";
        //将字符串转换为utf8格式的base64编码
        String base64str = base64.encodeToString(str.getBytes(StandardCharsets.UTF_8));
        System.out.println(base64str);
        //解码base64字符串为字节数组
        byte[] decode = base64.decode(base64str);
        //对byte[]数组进行utf8字符串编码
        System.out.println(new String(decode, StandardCharsets.UTF_8));
    }

    /**
     * 功能: 将base64格式的excel字符串逆向解码为excel
     */
    @Test
    public void test4() {
        String path1 = "E:\\kyee_temp\\work_temp\\excel\\2021-05-12 (2).log";
        String base64str = FileUtil.readString(path1, StandardCharsets.UTF_8);
        byte[] decodeArr = base64.decode(base64str);

        InputStream input = new ByteArrayInputStream(decodeArr);
        String outFilePath = "E:\\kyee_temp\\work_temp\\excel\\emp2.xls";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(outFilePath));
            IOUtils.write(decodeArr, fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
            IOUtils.closeQuietly(input);
        }
    }

}
